package com.xiaoyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoyang.common.BaseContext;
import com.xiaoyang.common.R;
import com.xiaoyang.domain.User;
import com.xiaoyang.service.UserService;
import com.xiaoyang.utils.SendEmail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @auther XiaoYang
 * @DATE 2022/12/17-20:19
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SendEmail sendEmail;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送邮箱验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取邮箱
        String email = user.getEmail();
        if (StringUtils.isNotEmpty(email)){
            //生成随机验证码
            String verifyCode = sendEmail.generateVerifyCode(4);
            log.info("code:{}",verifyCode);

            //发送验证码
            sendEmail.sendEmailCode(verifyCode,"316680963@qq.com",email);

            //需要将生成的验证码保存起来Session
            //session.setAttribute(email,verifyCode);

            //将生成的验证码缓存到redis中，并且设置有效期为一分钟
            redisTemplate.opsForValue().set(email,verifyCode,1, TimeUnit.MINUTES);

            return R.success("邮箱验证码发送成功");
        }

        return R.error("邮箱验证码发送失败");
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info("map:{}",map);
        //获取邮箱
        String email = map.get("email").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存验证码
        //String codeInSession = session.getAttribute(email).toString();

        //从Redis中获取缓存的验证码
        String codeInSession = redisTemplate.opsForValue().get(email).toString();


        //进行验证码比对（页面提交的和Session）
        if (codeInSession!=null && codeInSession.equals(code)){
            //如果能够比对成功，说明登陆成功
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                //判断当前email对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //如果用户登录成功，删除redis中缓存的验证码
            redisTemplate.delete(email);

            BaseContext.close();
            return R.success(user);
        }

        return R.error("登陆失败");
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("user");
        BaseContext.close();
        return R.success("退出成功");
    }

}
